/*
 * 显示普通的shared_ptr用法
 *
 * 结论:
 *  当向vector中增加shared_ptr对象后会增加引用计数
 *
 */
#include <iostream>
#include <memory>
#include <vector>

using namespace std;

class Base {
public:
	virtual ~Base() = default;
	virtual void foo() { std::cout << "Base::foo\n"; }
};

class Derived : public Base {
public:
	virtual void foo() { std::cout << "Derived::foo\n"; }
	~Derived() { std::cout << "Derived destructor\n"; }
};

std::shared_ptr<Base> create_fun() {
	std::shared_ptr<Base> ptr = std::make_shared<Derived>();
	return ptr;
}

class Example {
public:
    Example()
        : e(1)
    {
        cout << "Example Constructor..." << endl;
    }
    ~Example()
    {
        cout << "Example Destructor..." << endl;
    }

    int e;
};


int main() {
	// 测试基类指针虚函数调用
	auto ptr = create_fun();
	ptr->foo();  // 调用 Derived::foo

	return 0;

	// 测试引用计数
    shared_ptr<Example> pInt(new Example());
    cout << (*pInt).e << endl;
    cout << "pInt引用计数: " << pInt.use_count() << endl;

    shared_ptr<Example> pInt2 = pInt;
    cout << "pInt引用计数: " << pInt.use_count() << endl;
    cout << "pInt2引用计数: " << pInt2.use_count() << endl;
    std::vector<shared_ptr<Example> > vec;
    vec.push_back(pInt);
    cout << "vector.push_back 后pInt引用计数: " << pInt.use_count() << endl;
    cout << "vector.push_back 后 pInt2引用计数: " << pInt2.use_count() << endl;
}
